const {
  WORK_ORDER_STATUS,
  WORD_ORDER_OPERATION_TYPE,
  APPROVEAL_STATUS
} = require('../../../constant/index')
const {
  uploadSignInImg
} = require('../../../api/workOrder')
const {
  singIn,
  singInWithoutQrCode
} = require('../../../api/qrcode')
const { getUserBaseInformation } = require('../../..//utils/strorage')
const {
  to,
  openLoading,
  closeLoading,
  showToast,
  backParentLoad,
  routeWithToken,
  getEventData
} = getApp()
Component({
  options: {
    addGlobalClass: true
  },
  properties: {
    data: Object,
    type: String
  },
  data: {
    WORK_ORDER_STATUS,
    WORD_ORDER_OPERATION_TYPE,
    APPROVEAL_STATUS,
  },

  methods: {
    onClickTransfer() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/transfer-user-page/index?data=${data}&operationType=${WORD_ORDER_OPERATION_TYPE.WORK_ORDER_TRANSFER}`)
    },

    handleScan() {
      const self = this;
      wx.showActionSheet({
        itemList: ['扫码签到', '拍照签到'],
        success(res) {
          switch (res.tapIndex) {
            case 0:
              self.handleScanCodeClick();
              break;
            case 1:
              self.handlePacture()
          }
        }
      })
    },

    handleScanCodeClick() {
      const self = this;
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          const params = {
            workOrderId: self.data.data.workOrderId,
            scanContent: res.result
          }

          self.onToSingIn(params)
        },
        fail: (err) => {}
      });
    },

    async onToSingIn(params) {
      openLoading()
      const [err] = await to(singIn(params))
      closeLoading()

      if (!err) {
        showToast({
          message: '签到成功',
          type: 'success',
          mask: true,
          onClose: () => {
            setTimeout(() => {
              backParentLoad()
            }, 1000)
          }
        })
      }
    },

    handlePacture() {
      const self = this;
      wx.chooseMedia({
        sizeType: ['original'],
        sourceType: ['camera'],
        mediaType: ['image'],
        success(picture) {
          self.checkLocation().then(location => {
            self.submitImage(picture, location);
          })
        },
      });
    },
    async submitImage(picture, location) {
      openLoading('上传图片中');
      const [err, data] = await to(this.uploadImage(picture))

      if (!err) {
        const params = {
          workOrderId: this.data.data.workOrderId,
          signInImg: data,
          longitude: location.longitude,
          latitude: location.latitude
        }
        const [err1] = await to(singInWithoutQrCode(params))
        closeLoading()
        if (!err1) {
          showToast({
            message: '签到成功',
            type: 'success',
            mask: true,
            onClose: () => {
              setTimeout(() => {
                backParentLoad()
              }, 1000)
            }
          })
        }
      } else {
        closeLoading()
      }
    },
    async uploadImage(picture) {
      const imagePath = picture.tempFiles[0].tempFilePath;
      const [err, data] = await to(uploadSignInImg({
        filePath: imagePath
      }))
      if (!err) {
        return Promise.resolve(data)
      }
      return reject(err)
    },

    checkLocation() {
      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: "wgs84",
          success(res) {
            resolve(res)
          },
          fail: function (res) {
            wx.getSetting({
              success: function (res) {
                var statu = res.authSetting;
                if (!statu["scope.userLocation"]) {
                  wx.showModal({
                    title: "是否授权当前位置",
                    content: "需要获取您的地理位置，请确认授权，否则无法拍照签到",
                    success: function (tip) {
                      if (tip.confirm) {
                        wx.openSetting({
                          success: function (data) {
                            if (data.authSetting["scope.userLocation"] === true) {
                              wx.showToast({
                                title: "授权成功",
                                icon: "success",
                                duration: 1000
                              });
                              wx.getLocation({
                                type: "wgs84",
                                success(res1) {
                                  resolve(res1)
                                  //成功的执行方法
                                }
                              });
                            }
                          }
                        });
                      } else {
                        reject()
                      }
                    }
                  });
                }
              },
              fail: function (res) {
                wx.showToast({
                  title: "调用授权窗口失败",
                  icon: "success",
                  duration: 1000
                });
                reject()
              }
            });
          }
        });
      })

    },

    onClickSuspend() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/order-page-form/suspend-page/index?data=${data}`)
    },

    onClickRepairResultEnd() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/order-page-form/repair-result-page/index?data=${data}`)
    },

    onClickClose() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/order-page-form/order-close-page/index?data=${data}`)
    },

    showActionSheetCommon(list) {
      return new Promise((resolve, reject) => {
        wx.showActionSheet({
          itemList: list,
          success(res) {
            resolve(res.tapIndex)
          },
          fail(err) {
            reject(err)
          }
        })
      })
    },

    onClickMore() {
      let list = ['转单', '关闭', '挂起']
      this.showActionSheetCommon(list).then(res => {
        switch (res) {
          case 0:
            this.onClickTransfer();
            break;
          case 1:
            this.onClickClose()
            break;
          case 2:
            this.onClickSuspend()
            break;
        }
      })
    },

    onClickApprove() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/order-page-form/approve-page/index?data=${data}`)
    },

    onClickAppointmentAgain(event) {
      const {
        type
      } = getEventData(event);
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/order-page-form/appointnent-again-page/index?data=${data}&type=${ type }`)
    },

    onClickContactEnd() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/order-page-form/contacted-end/index?data=${data}`)
    },

    onClickDistribution() {
      const data = JSON.stringify(this.data.data);
      routeWithToken(`/page-common/transfer-user-page/index?data=${data}&operationType=${WORD_ORDER_OPERATION_TYPE.WORK_ORDER_DISTRIBUTION}`)
    },

    onClickCancelOrder() {
      const data = this.data.data;
      routeWithToken(`/page-common/order-page-form/order-cancel/index?workOrderId=${data.workOrderId}`)
    },

    onClickFeelback() {
      const data = this.data.data;
      routeWithToken(`/page-common/order-page-form/order-judge/index?workOrderId=${data.workOrderId}`)
    }
  }
})